home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / program / swagg_m.zip / MATH.SWG / 0034_BASE36 Conversion.pas < prev    next >
Pascal/Delphi Source File  |  1993-11-02  |  2KB  |  66 lines

  1. { Updated NUMBERS.SWG on November 2, 1993 }
  2.  
  3. {
  4. CORY ALBRECHT
  5.  
  6. > Can someone please show me how I would convert a base 10 number to
  7. > base 36? (The one used by RIP)
  8.  
  9. I presume you mean turning a Variable of Type Byte, Word, Integer, or
  10. LongInt to a String representation of that number in base 36? Just checking,
  11. since once I had someone who had two Word Variables who asked me how they
  12. could change Word1 to hexadecimal For putting it in Word2. The following
  13. code will turn any number from 0 to 65535 to a String representation of
  14. that number in any base from 2 to 36.
  15. }
  16.  
  17. Unit Conversion;
  18.  
  19. Interface
  20.  
  21. Const
  22.   BaseChars : Array [0..35] Of Char = ('0', '1', '2', '3', '4', '5',
  23.                                        '6', '7', '8', '9', 'A', 'B',
  24.                                        'C', 'D', 'E', 'F', 'G', 'H',
  25.                                        'I', 'J', 'K', 'L', 'M', 'N',
  26.                                        'O', 'P', 'Q', 'R', 'S', 'T',
  27.                                        'U', 'V', 'W', 'X', 'Y', 'Z');
  28.  
  29. { n - number to convert
  30.   b - base to convert to
  31.   s - String to store result in }
  32.  
  33. Procedure NumToStr(n : Word; b : Byte; Var s);
  34.  
  35. Implementation
  36.  
  37. Procedure NumToStr(n : Word; b : Byte; Var s);
  38. Var
  39.   i,
  40.   res,
  41.   rem : Word;
  42. begin
  43.   s := '';
  44.   if ((b < 2) or (b > 36)) Then
  45.     Exit;
  46.   res := n;
  47.   i   := 1;
  48.   { Get the digits of number n in base b }
  49.   Repeat
  50.     rem  = res MOD b;
  51.     res  := res div b;
  52.     s[i] := BaseChars[rem - 1];
  53.     Inc(s[0]);
  54.   Until rem = 0;
  55.   { Reverse s since the digits were stored backwards }
  56.   i := 1;
  57.   Repeat
  58.     s[i] := Chr(Ord(s[i]) xor Ord(s[Length(s) - (i - 1)]));
  59.     s[Length(s) - (i - 1)] := Chr(Ord(s[Length(s) - (i - 1)]) xor Ord(s[i]));
  60.     s[i] := Chr(Ord(s[i]) xor Ord(s[Length(s) - (i - 1)]));
  61.     Inc(i);
  62.   Until i >= (Length(s) - (i - 1));
  63. end;
  64.  
  65. end.
  66.